import time

import requests
import json
import re

course_stages_dict_lists = []


# 登录
def login():
    url = "https://crm.hongsong.info/gateway/api/fj-staff/account/v1/login"

    payload = json.dumps({
        "username": "fanchao@hongsong.club",
        "password": "k50ckd"
    })
    headers = {
        'authority': 'crm.hongsong.info',
        'loginsource': 'crm',
        'token': '[object Object]',
        'userid': 'null',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    token = response.json()['data']['token']
    return token

# 获取所有未冻结的正式课
def get_courses(token):
    url = "https://crm.hongsong.info/gateway/api/fjkt-crm-course-ui-interfaces/v2/course/course-page?courseTypeCode=3&frozenState=0&current=1&pageSize=300"

    payload = {}
    headers = {
        'authority': 'crm.hongsong.info',
        'loginsource': 'crm',
        'token': token,
        'userid': 'null',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)'
    }

    response = requests.request("GET", url, headers=headers, data=payload)

    text = response.text

    # 使用正则表达式模式匹配数字
    pattern = r'"id":(.*?),'
    matches = re.findall(pattern, text)

    today_live_course = []
    for match in matches:
        match.split(',')
        today_live_course.extend(match.split(','))

    print(today_live_course)
    print(len(today_live_course))

    today_live_course_not_test=[]
    # 处理数据，低于100，以及下面列表中的数据，去掉
    test_data_id = [1212, 1074, 1073, 1011, 986, 969, 968, 967, 966, 964, 961, 959, 908, 556, 524, 521, 284, 283, 152, 123, 122, 121, 120, 105, 104, 99, 96, 95, 94, 32, 31, 21]
    for i in today_live_course:
        if int(i)>100 and int(i) not in test_data_id:
            today_live_course_not_test.append(i)
    print('处理后的数据')
    print(today_live_course_not_test)
    print(len(today_live_course_not_test))
    return today_live_course_not_test


# 获取某个用户拥有的所有课程
def get_user_course(token, userNo='', nickName=None, ):
    url = "https://crm.hongsong.info/gateway/api/fjkt-crm-course-ui-interfaces/student/course/query/page"

    payload = json.dumps({
        "current": 1,
        "pageSize": 20,
        "nickName": nickName,
        "userNo": userNo,
        "userId": ""
    })
    headers = {
        'authority': 'crm.hongsong.info',
        'loginsource': 'crm',
        'token': token,
        'userid': 'null',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    studentCourseId = response.json()['data']['data'][0]['id']
    data = response.json()['data']['data'][0]['studentCourseRelations']
    my_courses = list()
    for i in range(len(data)):
        print(data[i]['courseId'], data[i]['courseName'])
        my_courses.append(data[i]['courseId'])

    return studentCourseId, my_courses


def get_course_stages(student_CourseId, courseIds, token, today_live_courses):
    for i in today_live_courses:
        if int(i) not in courseIds:
            # print('课程%s此账号没有' % i)
            url = "https://crm.hongsong.info/gateway/api/fjkt-crm-course-ui-interfaces/v2/course/get/stage/list/by/id?id=%s" % i

            payload = {}
            headers = {
                'authority': 'crm.hongsong.info',
                'loginsource': 'crm',
                'token': token,
                'userid': 'null',
                'User-Agent': 'Apifox/1.0.0 (https://apifox.com)'
            }

            response = requests.request("GET", url, headers=headers, data=payload)
            text = response.text

            # 使用正则表达式模式匹配数字
            pattern = r'"stageId":(.*?),"'
            matches = re.findall(pattern, text)

            # 打印所有匹配项
            stages_list = []
            course_stages_dict = {}
            course_stages_dict['studentCourseId'] = student_CourseId
            for match in matches:
                stages_list.append(int(match))
            course_stages_dict['courseId'] = i
            course_stages_dict['courseStageIds'] = stages_list  # !!!!!!!!!!!!!
            course_stages_dict_lists.append(course_stages_dict)

    return course_stages_dict_lists


def add_course(data, token):
    print(len(data))
    for i in data:
        # [1212, 1074, 1073, 1011, 986, 969, 968, 967, 966, 964, 961, 959, 908, 556, 524, 521, 284, 283, 152, 转换用户id, 122,
        #  121, 120, 105, 104, 99, 96, 95, 94, 32, 31, 21]

        print(i)
        # studentCourseId, courseId, courseStageIds
        url = "https://crm.hongsong.info/gateway/api/fjkt-crm-course-ui-interfaces/student/course/relation/add"

        payload = "{\"studentCourseId\":%s,\"studentCourseRelations\":[{\"courseId\":%s,\"courseStageIds\":%s,\"courseValidStartTime\":\"2021-10-01 00:00:00\",\"courseValidEndTime\":\"2025-10-01 23:59:59\"}]}" % (
            i['studentCourseId'], i['courseId'], i['courseStageIds'])
        headers = {
            'authority': 'crm.hongsong.info',
            'sec-ch-ua': '";Not A Brand";v="99", "Chromium";v="94"',
            'loginsource': 'crm',
            'sec-ch-ua-mobile': '?0',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.201.400 QQBrowser/12.0.5426.400',
            'content-type': 'application/json',
            'accept': 'application/json',
            'userid': 'null',
            'token': token,
            'sec-ch-ua-platform': '"Windows"',
            'origin': 'https://crm.hongsong.info',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://crm.hongsong.info/formal/studentCourse',
            'accept-language': 'zh-CN,zh;q=0.9'
        }

        # response = requests.request("POST", url, headers=headers, data=payload)
        #
        # print(response.text)
        # time.sleep(0.5)


if __name__=='__main__':
    token = login()
    today_live_courses = get_courses(token)
    # 0274072899    So
    # 0181777899 [旺柴]
    # 4079769899 seek
    # 9087130299 若相惜
    # 1197275899
    my_courses = get_user_course(userNo='1197275899', token=token)
    data = get_course_stages(my_courses[0], my_courses[1], token, today_live_courses)
    # print(data)
    add_course(data, token)
